package cn.jd.basic.service.impl;

import cn.jd.basic.anno.PreAuthorize;
import cn.jd.basic.eum.RequireTypeEum;
import cn.jd.basic.service.PermissionScanService;
import cn.jd.basic.util.SpringUtil;
import cn.jd.system.domain.Permission;
import cn.jd.system.mapper.PermissionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import java.lang.annotation.Annotation;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import static com.baomidou.mybatisplus.core.toolkit.ReflectionKit.getFieldValue;


@Service
public class PermissionScanServiceImpl implements PermissionScanService {
    // 扫描包的前缀
    private static final String PKG_PREFIX = "cn.jd.";
    // 扫描路径包后缀
    private static final String PKG_SUFFIX = ".controller";
    @Autowired
    private PermissionMapper permissionMapper;
    @Override
    public void scanPermission() {
       // 获取context
        ApplicationContext context = SpringUtil.getContext();
        // 遍历controller类
        Map<String, Object> allControllerMap = this.getAllController(context);
        // 遍历key类和value对象
        allControllerMap.forEach((k,v)->{
            Class<?> aClass = v.getClass();
            /**
             *  当前类不含有PreAuthorize注解，下次直接遍历，此时需要在controller类上也标记PreAuthorize注解，类上不打注解就可以不用该判断
             *
             */
            if (!aClass.isAnnotationPresent(PreAuthorize.class)) {
                return;
            }
            // 如果是动态代理类 那么它的方法也是动态代理方法，那么我们就不能直接使用getAnnotation获取到
            // 方法上的自定义注解在这里判断是否是代理类 是的话 通过获取父类的class获取到类的正常class文件
            if (Proxy.isProxyClass(aClass) || aClass.getName().contains("EnhancerBySpringCGLIB") ||
                    aClass.getName().contains("$$")) {
                aClass = aClass.getSuperclass();
            }
            // 获取到当前类所有的方法
            Method[] methods = aClass.getMethods();
            // 遍历方法获取到所有带有 PreAuthorize注解的方法
            List<Method> allMethods = Arrays.stream(methods).filter(me -> null != me.getAnnotation(PreAuthorize.class))
                    .collect(Collectors.toList());
            /**
             * 获取方法上面注解的值和方法的请求路径
              */
            // 获取类的请求路径
            String baseUrl = this.getClassPath(aClass);
            allMethods.forEach(method -> {
                // 获取方法上的请求路径
                String methodRequestMapping = this.getMethodRequestMapping(method);
                // 将类上的请求路径 + 方法上的请求路径 就是我们数据库存的url
                String allUrl = baseUrl + methodRequestMapping;
                // 获取方法上的注解的值
                PreAuthorize annotation = method.getAnnotation(PreAuthorize.class);
                String name = annotation.name();
                String sn = annotation.sn();
                // TODO 根据sn去查询 如果有就修改 没有就添加 但是目前是在遍历中进行 建议使用批量操作去优化代码
                Permission permission = initPermission(name, sn, allUrl);
                Permission tmpPermission = permissionMapper.findBySn(sn);
                if (null == tmpPermission){
                    permissionMapper.save(permission);
                }else {
                    permission.setId(tmpPermission.getId());
                    permissionMapper.update(permission);
                }
            });
        });

    }
    /**
     * 获取所有的controller类
     * @param context
     * @return
     */
    private Map<String, Object> getAllController(ApplicationContext context) {
        // 获取restController标记的类
        Map<String, Object> allControllerMap = context.getBeansWithAnnotation(RestController.class);
        // 获取controller标记的类
        allControllerMap.putAll(context.getBeansWithAnnotation(Controller.class));
        // TODO 如果controller还需要别的注解需要扫描的话 再添加即可
        return allControllerMap;
    }
    /**
     * 获取方法上的请求路径
     * @param method
     * @return
     */
    private String getMethodRequestMapping(Method method) {
        Annotation[] annotations = method.getAnnotations();
        Optional<Annotation> first = Arrays.stream(annotations).filter(anno -> RequireTypeEum.list().contains(anno.annotationType().getSimpleName()))
                .findFirst();
        if (!first.isPresent()){
            return "";
        }
        Annotation annotation = first.get();
        InvocationHandler invo = Proxy.getInvocationHandler(annotation);
        Map<String,String[]> map = (Map<String, String[]>) getFieldValue(invo, "memberValues");
        if (CollectionUtils.isEmpty(map) || null == map.get("value") || 0>= map.get("value").length){
            return "";
        }
        return map.get("value")[0];
    }
    /**
     * 获取字段的值
     * @param object
     * @param property
     * @param <T>
     * @return
     */
    public static <T> Object getFieldValue(T object, String property) {
        if (object != null && property != null) {
            Class<T> currClass = (Class<T>) object.getClass();
            try {
                Field field = currClass.getDeclaredField(property);
                field.setAccessible(true);
                return field.get(object);
            } catch (NoSuchFieldException e) {
                throw new IllegalArgumentException(currClass + " has no property: " + property);
            } catch (IllegalArgumentException e) {
                throw e;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 初始化Permission对象
     * @param name
     * @param sn
     * @param url
     * @return
     */
    private Permission initPermission(String name, String sn, String url){
        Permission permission = new Permission();
        permission.setName(name);
        permission.setUrl(url);
        permission.setSn(sn);
        return permission;
    }

    /**
     * 获取类的请求路径
     * @param aClass
     * @return
     */
    private String getClassPath(Class<?> aClass) {
        RequestMapping classRequestMapping = aClass.getAnnotation(RequestMapping.class);
        String[] classValue = classRequestMapping.value();
        if (null == classValue || classValue.length <= 0){
            return "";
        }
        StringBuffer sb = new StringBuffer();
        Arrays.stream(classValue).forEach(sb::append);
        return sb.toString();
    }

}
